<?php
/**
 * 微信授权登录
 * User: Acer
 * Date: 2022/7/9
 * Time: 13:47
 */

namespace app\wx\controller;
use app\core\MyController;
use app\wx\service\AuthorizeService;
use think\Cache;
use think\Log;
use think\Request;

class Authorize extends MyController
{
    protected $noNeedAction = ['*']; // 不需要校验控制器，通道
    // 操作前置
    protected $beforeActionList = ['my_initialize'];

    // 操作前置方法
    public function my_initialize()
    {

    }

    // 授权登录
    public function getLogin()
    {
        $data = input();
        header("Access-Control-Allow-Origin: *");
        if (!isset($data['code']) || empty($data['code'])) {
            // 跳转指定页面(接口地址)
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $jumpUrl = urlencode($http_type . config('server_name') .config('gz_h5'));
            Log::record("跳转参数：".$http_type . config('server_name') .config('gz_h5'));
            $url = config('authorize_url') . '?appid=' . config('gzAppId') . '&redirect_uri=' . $jumpUrl . '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
            header("Location: $url");
        } else {

            //  -------------  优先级一：是否传递token,获取user信息  ------------------
            $token = Request::instance()->header('token');
            // 解析token
            if ($token) {
                $uid = $this->checkToken($token);
                if ($uid) {
                    // 根据uid获取用户信息
                    $user = (new AuthorizeService())->s_getWxUserIdInfo($uid);
                    $user =obj_to_arr($user);
                    // 根据user_id 生成token
                    $token = $this->create_token($user['id'],$this->expire);
                    $user['token'] = $token;
                    $user['token_invalid']= time()+ ($this->expire - 10);
                    $user['is_authorize'] = 0;// 是否实名认证（1：是、0：否）
                    if(isset($user['idCardInfo']) && isset($user['idCardInfo']['mobile']) && isset($user['idCardInfo']['id_card'])){
                        $id_card = $user['idCardInfo']['id_card'];
                        $mobile = $user['idCardInfo']['mobile'];
                        if(!empty($id_card) && !empty($mobile) &&!empty($user['did'])) $user['is_authorize'] = 1;
                    }
                    _action_result(200, $user, '操作成功！');
                }
            }
            Log::record("=========token==========".$token);
            //  -------------  优先级二：授权获取用户信息  ------------------
            // 获取AccessToken
            $gzAuthorizeInfo = $this->getUserToken($data['code']);
            Log::record("=========获取AccessToken==========".json_encode($gzAuthorizeInfo));
            // 获取用户信息
            $user = $this->getWxUserInfo($gzAuthorizeInfo['openId'], $gzAuthorizeInfo['access_token']);
            $user =obj_to_arr($user);
            if (!$user) json_err(-210, ['获取用户信息失败！']);
            // 根据user_id 生成token
            $token = $this->create_token($user['id'],$this->expire);
            $user['token'] = $token;
            $user['token_invalid']= time()+ ($this->expire - 10);
            $user['is_authorize'] = 0;// 是否实名认证（1：是、0：否）
            if(isset($user['idCardInfo'])&& isset($user['idCardInfo']['mobile']) && isset($user['idCardInfo']['id_card'])){
                $id_card = $user['idCardInfo']['id_card'];
                $mobile = $user['idCardInfo']['mobile'];
                if(!empty($id_card) && !empty($mobile) &&!empty($user['did'])) $user['is_authorize'] = 1;
            }
            _action_result(200, $user, '操作成功！');
        }
    }

    // 通过 code 换取网页授权access_token
    public function getUserToken($code)
    {
        // 生成AccessToken
        $url = config('access_token_url') . '?appid=' . config('gzAppId') . '&secret=' . config('gzAppSecret') . '&code=' . $code . '&grant_type=authorization_code';
        //请求
        $res = send_request($url);
        $res = json_decode($res);
        if (isset($res->access_token)) {
            Cache::set('yxxgzAccessToken', $res->access_token, 7100);
            return [
                'openId' => $res->openid,
                'access_token' => $res->access_token,
            ];
        }
        json_err(-210, ['AccessToken 授权失败！']);
        exit();
    }

    // 获取用户信息
    public function getWxUserInfo($openId, $access_token)
    {
        // 判断是否是新用户
        $userInfo = (new AuthorizeService())->s_getUserInfo($openId);
        if ($userInfo) return $userInfo;
        // 获取用户信息
        $url = config('wx_user_info') . '?access_token=' . $access_token . '&openid=' . $openId . '&lang=zh_CN';
        $res = send_request($url);
        $res = (array)json_decode($res);
        $user = (new AuthorizeService())->s_install_info($res);
        if ($user) return $user;
        return false;
    }

    // 获取Access token
    public function get_token(){
        $token = Cache::get('yxxAccessToken');
        if($token) return $token;
        $url = config("gzh_access_token_url")."&appid=".config('gzAppId')."&secret=".config('gzAppSecret');
        $res = send_request($url);
        $res = (array)json_decode($res);
        if (isset($res['access_token'])) {
            Log::record("获取Access token====>".$res['access_token']);
            Cache::set('yxxAccessToken', $res['access_token'], 7100);
            return $res['access_token'];
        }
        return false;
    }

}
